import sys
import argparse
import csv
import file
import process

commands, labels = {}, {}
debug = 1


def main():
    if debug == 0:
        if len(sys.argv) != 2:
            print("Usage: python main.py filename")
            exit(1)
        parser = argparse.ArgumentParser(
            prog='sandbox_compiler',
            description='A simple compiler for the sandbox virtual machine.',
            epilog='Copyright (c),2024 by Smith Ding. All rights reserved.'
        )
        parser.add_argument('-f', '--filename', type=str,
                            help='the source file name')
        parser.add_argument('-t', '--type', type=str, default='code',
                            help='choose the target binary file type.')
        args = parser.parse_args()
    # else:
    #    filename = input('Enter filename:')
    # 读取设置文件
    with open("commands.csv", 'r') as f:
        reader = csv.reader(f)
        next(reader)
        commands = {row[0]: int(row[1], 16) for row in reader}
    with open("labels.csv", 'r') as f:
        reader = csv.reader(f)
        next(reader)
        labels = {row[0]: int(row[1]) for row in reader}
    filename = "../test/regtest.vas"
    # 读文件，初加工
    if debug == 0:
        filename = args.filename
    source = file.Reader(filename)
    process.removeIntend(source)
    process.removeComment(source)
    # 段拆分，按照Code-Data排序
    paras = process.split(source)
    paras.sort(key=lambda x: x.type)
    # 段加工，生成地址表
    for i in paras:
        i.setEntry()
        process.transform(i, labels)
        i.setAddress()
        i.putAddress(labels)
    # 指令部分编码
    for i in paras:
        if i.type == 1:
            break
        i.Encode(labels, commands)
    # 二进制化，合并到一个二进制序列中
    if debug == 1:
        type = input('Enter binary file type:')
    else:
        type = args.type
    byteCode = process.to_bytes(paras, type)
    with open(filename[:-4]+'.bin', 'wb') as f:
        f.write(byteCode)


if __name__ == "__main__":
    main()
